package tornadoj.web;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import java.util.List;

/**
 * Created by tinyms on 14-2-3.
 */
public class SimpleCache {
    public static String CACHE_NAME_DEFAULT = "tornadoj";
    public final static String CACHE_NAME_TEMPLATE = "tornadoj_layout_template";
    public final static String CACHE_NAME_MASTER_TEMPLATE = "tornadoj_layout_master_template";
    //
    private static CacheManager cacheManager = CacheManager.create();

    public static CacheManager getCacheManager() {
        return cacheManager;
    }

    public static Object getCache(String path, ICache iCache) {
        return getCache(path, iCache, CACHE_NAME_DEFAULT);
    }

    public static Object getCache(String path, ICache iCache, String name) {
        Object cacheItem = getCache(path, name);
        if (cacheItem != null) {
            return cacheItem;
        }
        cacheItem = iCache.doInCache();
        setCache(path, cacheItem, name);
        return cacheItem;
    }

    public static Object getCache(String path) {
        return getCache(path, CACHE_NAME_DEFAULT);
    }

    public static Object getCache(String path, String name) {
        Cache c = cacheManager.getCache(name);
        if (c == null) {
            return null;
        }
        Element e = c.get(path);
        if (e == null) {
            return null;
        }
        return e.getObjectValue();
    }

    public static void setCache(String path, Object data) {
        setCache(path, data, CACHE_NAME_DEFAULT);
    }

    public static void setCache(String path, Object data, String name) {
        Cache c = cacheManager.getCache(name);
        if (c != null) {
            c.put(new Element(path, data));
        }
    }

    public static void removeCache(String path) {
        removeCache(path, CACHE_NAME_DEFAULT);
    }

    public static void removeCache(String path, String name) {
        Cache c = cacheManager.getCache(name);
        if (c == null) {
            return;
        }
        List keys = c.getKeys();
        for (Object key : keys) {
            if (String.valueOf(key).startsWith(path)) {
                c.remove(key);
            }
        }
    }

    public static void clear(){
        Cache c = cacheManager.getCache(CACHE_NAME_DEFAULT);
        c.removeAll();
    }

    public static void clear(String name){
        Cache c = cacheManager.getCache(name);
        c.removeAll();
    }

    /**
     * 注册永久缓存,手动更新或清除缓存
     * @param name
     */
    public static void registerCacheForever(String name) {
        Cache c = new Cache(name, 1, true, true, 0, 0, true, 0);
        cacheManager.addCache(c);
    }
}
